#ifndef QUERYMICROMAN_H
#define QUERYMICROMAN_H

#include <QObject>
#include <QMutex>
#include <QTcpSocket>
#include <QTimer>

#include "common.h"

template < typename T > class Locker
{
    T * Obj;
    QMutex * Mtx;
    Locker( const Locker & l ) {}
    Locker & operator=( const Locker & l ) {}

public:
   Locker( volatile T * obj )
       : Obj( const_cast< T* >( obj ) ),
         Mtx( new QMutex() )
   {
       Mtx->lock();
   }

   ~Locker()
   {
       Mtx->unlock();
       delete Mtx;
   }

   T & operator*() { return *Obj; }
   T * operator->() { return Obj; }

};


class QueryMicroMan : public QObject
{
    Q_OBJECT

    quint64 maxtimeout;
    QTcpSocket * sock;
    QTimer * timer;
    QMutex mtx;
    QTextCodec * codec;

    Locker< QueryMicroMan > * locker;

    bool waitForEnd;

public:
    explicit QueryMicroMan( QObject *parent = 0 );

    volatile bool locked;
    QString outStr;
    void setTimeout( quint64 t ) { maxtimeout = t; }
    bool isConnected() { return sock->isOpen(); }

private:
    void LOCK();
    void UNLOCK();

signals:
    void sgnDone();
    void sgnError();
    void sgnSendResponse( QString txt );
    void sgnConnected();
    void sgnDisconnected();
    
private slots:
    void onConnected();
    void onReadyRead();
    void onTimeout();

public slots:
    void Connect( QString h, quint16 p );
    void Disconnect();
    void ExecCmd( const QString cmd, bool WaitForEnd = false );
};

#endif // QUERYMICROMAN_H
